<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { getUsers, getStudent, getOrganize } from '../../util/SessionUtil'
import regexUtil from '../../util/RegexUtil'
import $ from 'jquery'
import 'bootstrap/dist/js/bootstrap'
import { DateTime } from 'luxon'
import { db } from '../../db/db'

const salvationTypeData: any = ref([])

const form = ref({
  salvationTypeId: '',
  petSituation: '',
  realName: '',
  phoneNumber: '',
  qq: '',
  weixin: '',
  address: ''
})
const formErr = ref({
  salvationTypeId: false,
  petSituation: false,
  realName: false,
  phoneNumber: false,
  address: false
})
const formMsg = ref({
  salvationTypeId: '',
  petSituation: '',
  realName: '',
  phoneNumber: '',
  address: ''
})

const imagesErr = ref('')

function checkSalvationTypeId() {
  formErr.value.salvationTypeId = false
  formMsg.value.salvationTypeId = ''
  if (form.value.salvationTypeId === '') {
    formErr.value.salvationTypeId = true
    formMsg.value.salvationTypeId = '请选择宠物类型'
    return false
  }
  return true
}

function checkPetSituation() {
  formErr.value.petSituation = false
  formMsg.value.petSituation = ''
  if (form.value.petSituation === '') {
    formErr.value.petSituation = true
    formMsg.value.petSituation = '宠物情况不能为空'
    return false
  }
  return true
}

function checkRealName() {
  formErr.value.realName = false
  formMsg.value.realName = ''
  if (form.value.realName === '') {
    formErr.value.realName = true
    formMsg.value.realName = '联系人不能为空'
    return false
  }
  return true
}

function checkPhoneNumber() {
  formErr.value.phoneNumber = false
  formMsg.value.phoneNumber = ''
  if (form.value.phoneNumber === '') {
    formErr.value.phoneNumber = true
    formMsg.value.phoneNumber = '手机号不能为空'
    return false
  } else {
    if (!regexUtil.mobile.test(form.value.phoneNumber)) {
      formErr.value.phoneNumber = true
      formMsg.value.phoneNumber = '手机号11位数字'
      return false
    }
  }
  return true
}

function checkAddress() {
  formErr.value.address = false
  formMsg.value.address = ''
  if (form.value.address === '') {
    formErr.value.address = true
    formMsg.value.address = '联系地址不能为空'
    return false
  }
  return true
}

interface FileWithURL {
  file: File
  url: string
}

const fileInput = ref<HTMLInputElement>()
const fileMap = ref(new Map<string, FileWithURL>())

const imgUrls = ref(new Array<any>())

/**
 * 当 input[type='file'] 变化，即用户选择了文件的使用，将其以文件名为 key ，暂时保存在 fileMap 中；
 * 注意， input 上的 files 属性，只保存用户打开了文件选择框，并且选择了文件后，这一时刻的文件
 * 也就是说，用户每次选择执行的都是 replace 的操作，因此，我们使用 map 来维护用户多次选择的所有文件，以及一些手动删除的操作
 */
const onFileChange = function (this: HTMLInputElement) {
  const files = this.files || []
  for (const file of files) {
    const url = URL.createObjectURL(file)
    fileMap.value.set(file.name, { file, url })


    fileToBase64(file, function (base64:any) {
      imgUrls.value.push({ url: base64 })
    });

  }
}

function fileToBase64(file:any, callback:any) {
  const reader = new FileReader();
  reader.onload = function (event:any) {
    callback(event.target.result);
  };
  reader.readAsDataURL(file);
}

/** 点击模拟的文件选择触发按钮，触发真实的文件选择的响应事件 */
const clickFileIput = () => {
  fileInput.value?.click()
  $('#fileModal').modal('hide')
}

const users = getUsers()

onMounted(async () => {
  salvationTypeData.value = await db.salvationType.toArray()

  fileInput.value?.addEventListener('change', onFileChange)

  if (users) {
    form.value.realName = users.realName
    if (users.usersTypeId == 4) {
      const student = await getStudent(users.username)
      form.value.phoneNumber = student[0].phoneNumber
      form.value.qq = student[0].qq ? student[0].qq : ''
      form.value.weixin = student[0].weixin ? student[0].weixin : ''
    } else if (users.usersTypeId == 3) {
      const organize = await getOrganize(users.username)
      form.value.phoneNumber = organize[0].responsiblePersonPhoneNumber
    }
  }
})

const onSubmit = () => {
  const formData = new FormData()
  for (const extendFile of fileMap.value.values()) {
    formData.append(extendFile.file.name, extendFile.file)
  }
  // axios.post("your server address", formData)
}

const fileType = () => {
  $('#fileModal').modal('show')
}

const toCapture = () => {
  initCamera()
  $('#fileModal').modal('hide')
  $('#captureModal').modal('show')
}

const initCamera = () => {
  // 检查浏览器是否支持getUserMedia API
  if (navigator.mediaDevices.getUserMedia) {
    // 设置拍照参数
    const constraints = {
      video: {
        width: 800,
        height: 400
      }
    };

    // 获取视频流
    navigator.mediaDevices.getUserMedia(constraints)
      .then(function (stream:any) {
        // 将视频流设置为video元素的源
        const video:any = document.querySelector('#videoEle')
        if (video) {
          if ("srcObject" in video) {
            video.srcObject = stream
          } else {
            // 老的浏览器可能没有srcObject
            video.src = window.URL.createObjectURL(stream)
          }
          video.play() // 播放视频
        }

      })
      .catch(function (error) {
        console.log("获取摄像头错误：", error)
      });
  } else {
    alert("你的浏览器不支持摄像头调用");
  }
}


const captureButton = () => {
  const video:any = document.querySelector('#videoEle')
  const canvas:any = document.querySelector('#canvasElement')
  if (canvas) {
    const context = canvas.getContext('2d');

    // 设置canvas的宽高
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // 绘制当前视频流到canvas
    context.drawImage(video, 0, 0, canvas.width, canvas.height);

    // 将canvas转换为base64图片
    const img = canvas.toDataURL('image/png');

    // 可以将img的src设置为base64，展示图片
    imgUrls.value.push({ url: img })
  }

  $('#captureModal').modal('hide')

}


const delImg = (index: any) => {
  imgUrls.value.splice(index, 1)
}

const submitForm = async () => {
  if (!checkSalvationTypeId()) {
    return false
  }

  if (!checkPetSituation()) {
    return false
  }

  if (!checkRealName()) {
    return false
  }

  if (!checkPhoneNumber()) {
    return false
  }

  if (!checkAddress()) {
    return false
  }

  if (imgUrls.value.length <= 0) {
    imagesErr.value = "请上传宠物图片"
  }

  const salvationId = uuidv4()
  db.salvation.add({
    salvationId: salvationId,
    salvationTypeId: Number(form.value.salvationTypeId),
    petSituation: form.value.petSituation,
    username: users.username,
    createDate: DateTime.now().toFormat('yyyy-LL-dd HH:mm:ss'),
    address: form.value.address,
    phoneNumber: form.value.phoneNumber,
    qq: form.value.qq,
    weixin: form.value.weixin,
    salvationStatus: 0
  })

  for (let pi in imgUrls.value) {
    db.petImage.add({
      petImageId: uuidv4(),
      petImageUrl: imgUrls.value[pi].url,
      salvationId: salvationId
    })
  }

  const ost = await db.organizeSalvationType.where('salvationTypeId').equals(Number(form.value.salvationTypeId)).toArray()

  let randomOrganizeId = -1
  if (ost.length > 0) {
    const randomOstIndex = Math.floor(Math.random() * ost.length)
    randomOrganizeId = ost[randomOstIndex].organizeId
  }

  db.petSalvationPlan.add({
    petSalvationPlanId: uuidv4(),
    node: '待救助',
    situation: '待鉴别',
    organizeId: randomOrganizeId,
    salvationId: salvationId,
    petSalvationPlanDate: DateTime.now().toFormat('yyyy-LL-dd HH:mm:ss')
  })

  form.value.salvationTypeId = ''
  form.value.petSituation = ''
  form.value.address = ''
  imgUrls.value.splice(0, imgUrls.value.length)
  $('#successModal').modal('show')
}

const closeModal = () => {
  $('#successModal').modal('hide')
  window.location.href = "/"
}
</script>
<template>
  <div class="container pt-5 pb-5">
    <section class="pt-5 pb-5" data-aos="fade-up">
      <div class="jumbotron jumbotron-fluid">
        <div class="container">
          <h1 class="display-4">发起救助</h1>
          <p class="lead">传递爱心，让每个生命都值得尊重——救助站，为你点亮生命之光。</p>
        </div>
      </div>
      <div class="row">
        <div class="col-12">
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label for="salvationTypeId" class="font-weight-bold">宠物类型</label>
              <select class="form-control" :class="formErr.salvationTypeId ? 'is-invalid' : ''"
                v-model="form.salvationTypeId" @change="checkSalvationTypeId">
                <option value="">请选择类型</option>
                <option v-for="salvationType in salvationTypeData" :value="salvationType.salvationTypeId">
                  {{ salvationType.salvationTypeName }}
                </option>
              </select>
              <div class="invalid-feedback">
                {{ formMsg.salvationTypeId }}
              </div>
            </div>
            <div class="form-group">
              <label for="petSituation" class="font-weight-bold">宠物情况</label>
              <textarea class="form-control" rows="3" placeholder="请简单描述宠物当前情况，便于及时救助"
                :class="formErr.petSituation ? 'is-invalid' : ''" v-model.trim="form.petSituation"
                @blur="checkPetSituation"></textarea>
              <div class="invalid-feedback">
                {{ formMsg.petSituation }}
              </div>
            </div>
            <div class="form-group">
              <label for="address" class="font-weight-bold">联系人</label>
              <input type="text" class="form-control" placeholder="联系人" :class="formErr.realName ? 'is-invalid' : ''"
                v-model.trim="form.realName" @blur="checkRealName" />
              <div class="invalid-feedback">
                {{ formMsg.realName }}
              </div>
            </div>
            <div class="form-group">
              <label for="address" class="font-weight-bold">联系方式</label>
              <div class="form-row">
                <div class="col">
                  <input type="text" class="form-control" placeholder="手机号（必填）"
                    :class="formErr.phoneNumber ? 'is-invalid' : ''" v-model.trim="form.phoneNumber" readonly="true">
                  <div class="invalid-feedback">
                    {{ formMsg.phoneNumber }}
                  </div>
                </div>
                <div class="col">
                  <input type="text" class="form-control" placeholder="QQ（选填）" v-model.trim="form.qq">
                </div>
                <div class="col">
                  <input type="text" class="form-control" placeholder="微信（选填）" v-model.trim="form.weixin">
                </div>
              </div>

              <small class="form-text text-muted">我们将会通过联系方式尽快与您联系</small>
            </div>
            <div class="form-group">
              <label for="address" class="font-weight-bold">联系地址</label>
              <input type="text" class="form-control" placeholder="联系地址" :class="formErr.address ? 'is-invalid' : ''"
                v-model.trim="form.address" @blur="checkAddress" />
              <div class="invalid-feedback">
                {{ formMsg.address }}
              </div>
              <small class="form-text text-muted">请填写详细地址</small>
            </div>
            <div class="form-group">
              <label class="font-weight-bold">宠物图片</label>
              <div>
                <input ref="fileInput" type="file" placeholder="选择你的文件" style="display: none" multiple accept="image/*"/>
                <div class="file-input">
                  <div v-for="(item, index) in imgUrls" class="img-preview">
                    <div>
                      <button type="button" class="close" @click="delImg(index)">
                        <span aria-hidden="true">&times;</span>
                      </button>
                      <img :src="item.url" />
                    </div>

                  </div>
                  <font-awesome-icon icon="plus" class="select-file" @click="fileType" />
                </div>
              </div>
            </div>
            <div class="text-center text-danger mb-3">
              {{ imagesErr }}
            </div>
            <div class="text-center">
              <button type="submit" class="btn btn-primary">提 交</button>
            </div>
          </form>
        </div>
      </div>
    </section>
  </div>

  <!-- Modal -->
  <div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title text-success" id="successModalLabel">发起救助成功</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          请耐心等待，客服稍后会联系您了解详细情况。
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeModal">确定</button>
        </div>
      </div>
    </div>
  </div>

  <!--拍照选项-->
  <div class="modal fade" id="fileModal" tabindex="-1" aria-labelledby="fileModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="fileModalLabel">文件获取方式</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <button type="button" class="btn btn-primary btn-round btn-block shadow-sm" @click="toCapture">拍 照</button>
          <button type="button" class="btn btn-primary btn-round btn-block shadow-sm"
            @click="clickFileIput">从本地上传</button>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="captureModal" tabindex="-1" aria-labelledby="captureModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="captureModalLabel">拍照上传</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <video autoplay playsinline id="videoEle"></video>
          <canvas style="display: none;" id="canvasElement"></canvas>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-primary" @click="captureButton">拍照</button>
        </div>
      </div>
    </div>
  </div>

</template>
<style scoped>
.file-input {
  display: flex;
  flex-direction: row;
  padding: 12px;

  .img-preview {
    position: relative;
    margin: 0 6px;

    img {
      width: 100px;
      height: 100px;
    }
  }

  .select-file {
    width: 100px;
    height: 100px;
    color: #eee;
    font-size: 70px;
    line-height: 100px;
    text-align: center;
    background-color: white;
    border: 1px solid #ddd;
    border-radius: 8px;
  }
}

#videoEle {
  width: 100%;
  /* 宽度自适应 */
  height: auto;
  /* 高度自适应 */
  object-fit: contain;
  /* 保持视频的宽高比例 */
}
</style>
